package com.elephant.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elephant.pojo.Weather;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WeatherJsonService {

    String jsonWeather;
    String key="weather api key";

    public List<Weather> getWeatherInfo(String cityName) throws IOException {
        //获取http客户端
        CloseableHttpClient client = HttpClients. createDefault();
        //通过httpget方式来实现我们的get请求
        HttpGet httpGet = new HttpGet( "http://apis.haoservice.com/weather?key="+key+"&cityname="+cityName);
        CloseableHttpResponse Response = client.execute(httpGet);

        HttpEntity entity = Response . getEntity();
        //通过EntityUtils 来将我们的数据转换成字符串
        String str = EntityUtils.toString(entity, "UTF-8");
        System.out.println(str);

        List<Weather> weathers = new ArrayList<Weather>();
        JSONObject json = JSON.parseObject(str);
        String name = json.getString("result");
        JSONObject json2 = JSON.parseObject(name);
        String future = json2.getString("future");
        JSONArray jsonArr = JSON.parseArray(future);
        for (int i = 0; i < 7; i++) {
            JSONObject jsonObj1 = jsonArr.getJSONObject(i);
            Weather weather = JSON.parseObject(jsonObj1.toJSONString(),Weather.class);
            weathers.add(weather);
        }

        return weathers;
    }
}
